//
//  LDHomePageViewController.m
//  LuDaoJinFu
//
//  Created by dzjf on 2017/2/28.
//  Copyright © 2017年 dzjf. All rights reserved.
//

#import "LDHomePageViewController.h"
#import "homeTableViewCell.h"
#import "LDHomeHeadView.h"
#import <SDCycleScrollView.h>
#import "AdDetail.h"
#import "DZQualityViewController.h"
#import "HomeFootSecutyView.h"
#import "AnnounceDetailVC.h"
@interface LDHomePageViewController ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate>
{
    NSMutableArray *dataArray;
    NSMutableArray *adArray;
    NSMutableArray *bulletinArray;
    LDHomeHeadView *_headView;
}
@property (copy, nonatomic) NSString *cachePath;
@property (strong, nonatomic) UITableView *tableView;
@end

@implementation LDHomePageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = BACKGROUND_COLOR;
    dataArray = [NSMutableArray array];
    adArray = [NSMutableArray array];
    bulletinArray = [NSMutableArray array];
    [self setTableView];
    [self setInformation];
    [self presentToGestureView];
}

#pragma mark - data

- (void)setInformation {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    _cachePath = [[paths firstObject]stringByAppendingString:@"/MyCache"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:_cachePath]) {
        //从本地读缓存文件
        NSData *data = [NSData dataWithContentsOfFile:_cachePath];
        if (data) {
            id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            [self loadData:json];
        }
    }
    DZRequestUtil *request = [[DZRequestUtil alloc] init];
    request.requestUrl = @"Index/getIndexData";
    request.httpMethod = @"GET";
    [DZNetAPI request:request success:^(id response) {
        [self.tableView.mj_header endRefreshing];
        NSLog(@"%@",response);
        DZResponse *model = [DZResponse mj_objectWithKeyValues:response];
        if (model.rt == 1) {
            NSData *data = [NSJSONSerialization dataWithJSONObject:response options:NSJSONWritingPrettyPrinted error:nil];
            [data writeToFile:_cachePath atomically:YES];
            [self loadData:response];
        }
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)loadData:(id)response {
    DZResponse *res = [DZResponse mj_objectWithKeyValues:response];
    if (res.rt == 1) {
        [dataArray removeAllObjects];
        [adArray removeAllObjects];
        dataArray = [HomeCellModel mj_objectArrayWithKeyValuesArray:res.data[@"productList"]];
        [self.tableView reloadData];
        
        bulletinArray = [DZHomeBulletinModel mj_objectArrayWithKeyValuesArray:res.data[@"bulletin"]];
        adArray = [DZHomeAdverModel mj_objectArrayWithKeyValuesArray:res.data[@"rollAdsList"]];
        [self updateAdverAction:response];
    }
}

#pragma mark - tableview

- (void)setTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -64, SCREEN_WIDTH, SCREEN_HEIGHT+64) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.backgroundView = nil;
    self.tableView.backgroundColor = BACKGROUND_COLOR;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:homeTableViewCells bundle:nil] forCellReuseIdentifier:homeTableViewCells];
    self.tableView.tableHeaderView = [self setTableHeadView];
    self.tableView.tableFooterView = [self setTableFootView];
    self.tableView.mj_header = [MJDIYHeader headerWithRefreshingBlock:^{
        [self setInformation];
    }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    homeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:homeTableViewCells];
    HomeCellModel *model = dataArray[indexPath.section];
    [cell cellReloadData:model];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeCellModel *model = dataArray[indexPath.section];
    if (model.remaining_investment_amount > 0) {
        DZQualityViewController *financialDetail = [[DZQualityViewController alloc] init];
        financialDetail.productId = [model.id integerValue];
        [financialDetail setupTitleView:model.name];
        financialDetail.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:financialDetail animated:YES];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 94;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 6;
}

#pragma mark - headview
- (UIView *)setTableHeadView {
    _headView =  [[[NSBundle mainBundle] loadNibNamed:@"LDHomeHeadView" owner:nil options:nil]objectAtIndex:0];
    CGFloat height = 40 + SCREEN_WIDTH * 0.48;
    _headView.frame = CGRectMake(0, 0, SCREEN_WIDTH, height);
    _headView.scroller.delegate = self;
    _headView.titleScroll.delegate = self;
    return _headView;
}

- (void)updateAdverAction:(id )responseObject {
    NSString *allPeople = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"gmrc"]];
    NSString *allMoney = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"ljtzje"]];
    _headView.allPeople.text = [DZNsstringUtil stringSubToNumber:allPeople];
    _headView.allMoney.text = [DZNsstringUtil stringSubToNumber:allMoney];
    
    NSMutableArray *imageArray = [NSMutableArray array];
    for (NSInteger i = 0; i < adArray.count; i ++ ) {
        DZHomeAdverModel *model = adArray[i];
        [imageArray addObject:model.img_path];
    }
    _headView.scroller.imageURLStringsGroup = imageArray;
    if (imageArray.count < 2) {
        _headView.pageControll.hidden = YES;
    }else {
        _headView.pageControll.hidden = NO;
        [_headView scrollToIndex:0];
    }
    NSMutableArray *titleArray = [NSMutableArray array];
    for (NSInteger i = 0; i < bulletinArray.count; i ++ ) {
        DZHomeBulletinModel *model = bulletinArray[i];
        [titleArray addObject:model.title];
    }
    _headView.titleScroll.titlesGroup = titleArray;
}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    if (_headView.scroller == cycleScrollView) {
        AdDetail *ad = [[AdDetail alloc] init];
        ad.hidesBottomBarWhenPushed = YES;
        DZHomeAdverModel *model = adArray[index];
        [ad setupTitleView:model.title];
        ad.urlStr = model.url;
        [self.navigationController pushViewController:ad animated:YES];
    }else if (_headView.titleScroll == cycleScrollView) {
        AnnounceDetailVC *vc = [[AnnounceDetailVC alloc] init];
        DZHomeBulletinModel *model = bulletinArray[index];
        vc.idStr = [NSString stringWithFormat:@"%ld",(long)model.id];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index {
    [_headView scrollToIndex:index];
}

- (UIView *)setTableFootView {
    CGFloat  height = 95;
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, height)];
    footer.backgroundColor = [UIColor clearColor];
    HomeFootSecutyView *homeView = [HomeFootSecutyView loadView];
    homeView.frame = CGRectMake(21, 22, SCREEN_WIDTH -42 ,75);
    [footer addSubview:homeView];
    
    return footer;
}

#pragma mark - gesture
- (void)setGestureLock {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(presentToGestureView) name:@"gestureLockNotification" object:nil];
    if (userValue(HAVEGESTUREPWD) != nil) {
        if ([userValue(ISLOGIN) boolValue] == YES && ([userValue(HAVEGESTUREPWD) integerValue] == 1 || [userValue(HAVEGESTUREPWD) integerValue] == 3)) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"gestureLockNotification" object:nil];
        }
    }
}

- (void)presentToGestureView {
    if ([userValue(HAVEGESTUREPWD) integerValue] == 1 || [userValue(HAVEGESTUREPWD) integerValue] == 3) {
        GesturePassword *gesture = [[GesturePassword alloc] init];
        gesture.gestureType = GestureTypeUnlock;
        [self presentViewController:[[MNaviCtrl alloc] initWithRootViewController:gesture] animated:YES completion:nil];
    }
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
